package com.example.gybicycle.common.security;

import  com.alibaba.fastjson.JSONObject;
import com.example.gybicycle.common.entity.Result;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jodd.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;

import java.io.IOException;

/**
 * @author jqllxew
 * 2020/10/22.
 */
@Slf4j
public class AuthFilter extends BasicHttpAuthenticationFilter {
    public static final String HEADER = "Authorization";
    /**
     * 这个方法返回null的话会直接抛出异常，进入isAccessAllowed（）的异常处理逻辑。
     */
    @Override
    protected AuthenticationToken createToken(ServletRequest servletRequest, ServletResponse servletResponse) {
        HttpServletRequest request = WebUtils.toHttp(servletRequest);
        String token = findToken(request);
        if (StringUtil.isNotEmpty(token)){
            return new Token(token);
        }
        return null;
    }
    /**
     * 父类会在请求进入拦截器后调用该方法，返回true则继续，返回false则会调用onAccessDenied()。
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object mappedValue) {
        boolean allowed = false;
        try {
            allowed = executeLogin(servletRequest, servletResponse);
        } catch (IllegalStateException e) { //not found any token
            log.error("Not found any token");
        } catch (Exception e) {
            log.error("Error occurs when login", e);
        }
        return allowed;
    }




    /**
     * 如果这个Filter在之前isAccessAllowed（）方法中返回false,则会进入这个方法。
     */
    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws IOException {
        String result = JSONObject.toJSONString(Result.loginOut());
        servletResponse.setCharacterEncoding("utf-8");
        servletResponse.setContentType("application/json");
        servletResponse.getWriter().write(result);
        return false;
    }
    /**
     * 如果Shiro Login认证成功，会进入该方法，等同于用户名密码登录成功
     */
    @Override
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) {
        return true;
    }
    public static String findToken(HttpServletRequest request){
        String token = request.getHeader(HEADER);
        if (StringUtil.isEmpty(token)){
            Cookie[] cookies = request.getCookies();
            if (cookies != null){
                for(Cookie c : cookies){
                    if (HEADER.equals(c.getName())){
                        return c.getValue();
                    }
                }
            }
        }
        return token;
    }
}
